//
//  WTComposeViewController.swift
//  WTSinaWeibo
//
//  Created by  Wellim on 16/7/3.
//  Copyright © 2016年  Wellim. All rights reserved.
//

import UIKit

class WTComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    
        setUpUI()
        
    }

    // MARK: - 设置视图
    private func setUpUI(){
    
        view.backgroundColor = UIColor.whiteColor()
     
        setUpNav()
        
          // 添加控件
        view.addSubview(composeTextView)
        view.addSubview(composeToolbar)
        composeTextView.addSubview(pictureView)
        
        // 添加约束
        // 在ios7 以后 系统检测出有导航栏 textView 的文字下移
        composeTextView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
            
        }
       
        composeToolbar.snp_makeConstraints { (make) in
            
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) in
        
            make.left.equalTo(composeTextView).offset(10)
            make.top.equalTo(composeTextView).offset(100)
            make.size.equalTo(CGSize(width: kScreenWidth - 20, height: kScreenWidth - 20))
            
        }
        // 弹出相册
        pictureView.composePictureViewClosure = {[weak self]()->() in
        
         self?.selectImages()
        
        }
    
        
//         // 监听composeToolbar 中的按钮店家
        composeToolbar.closure = {[weak self](type: WTComposeToolbarType) ->() in
            switch type {
            case .Picture:
                self?.selectImages() // 如果实现代理方法 系统将不再帮程序员关闭控制器
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emoticon:
//                print("表情")
                self?.selectKeyboard()
            case .Add:
                print("+")

            }
            
            
       }
        
        // 通过系统通知监听键盘
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
         // 接收表情键盘删除按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteClick", name: EmoticonDeleteNoti, object: nil)
        
         // 接收表情键盘表情按钮通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonBtnClick:", name: EmoticonButtonNoti, object: nil)
    
}
    
    // MARK: - 监听emoticonBtnClick的事件
    func emoticonBtnClick(noti:NSNotification)  {
        
         // 判断object 是否为nil  而且能否转成emoticon
        guard let emoticon = noti.object as? WTEmoticon else{
        
          return
        }
           //是emoji 表情
        if emoticon.isEmoji {
            
            
            composeTextView.insertText(((emoticon.code ?? "") as NSString).emoji())
        
        }else{
          
            // 纪录composeTextView 上一次富文本纪录
            let oldAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            // 图片表情
            // 文本附件（使用它 需要设置bounds）
            let att = WTTextAttachment()
            // 设置emoticon
            att.emoticon = emoticon
            // 设置image
            let path = emoticon.path ?? ""
            let png = emoticon.png ?? ""
            let name = path + png
            
            att.image = UIImage(named: name, inBundle: WTEmoticonTools.sharedEmoticonTools.emotionBundle, compatibleWithTraitCollection: nil)
            // 行高
            let lineHeight = composeTextView.font?.lineHeight
            // 设置bounds
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight!, height: lineHeight!)
            
            // 创建一个不可变的富文本
            let attr = NSAttributedString(attachment: att)
            
            // 获取选中的光标
            let selectRange = composeTextView.selectedRange
            
            
            // 01拼接方式不可取
            //oldAttr.appendAttributedString(attr)
            // 02插入方式不可取
            //oldAttr.insertAttributedString(attr, atIndex: selectRange.location)
            // 03 替换
            oldAttr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            // 设置富文本的font
            
            oldAttr.addAttributes([NSFontAttributeName :composeTextView.font!], range:NSRange(location: 0, length: oldAttr.length))
            
            composeTextView.attributedText = oldAttr
            
           // 更改composeTextView光标
            composeTextView.selectedRange = NSRange(location: selectRange.location + 1, length:0)
           // 发送一个系统通知 隐藏或者显示textView 的站位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            // 调用代理方法使右侧按钮改变状态
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        
        }
        
        
        
    }
    
    
    
    // 删除按钮事件
    func deleteClick()  {
        
        composeTextView.deleteBackward()
    }
    
    
    // 监听键盘frame改变
    func keyboardWillChangeFrame(noti:NSNotification)  {
        // NSRect mac开发中用得 我们移动端开发CGRect 需要我们先把NSRect 转成NSValue
        // 如果rect
        let rect = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue()
        
        // 更新toolbar 约束
        composeToolbar.snp_updateConstraints { (make) in
            
            make.bottom.equalTo(view).offset(rect.origin.y - kScreenHeight)
            
        }
        
       UIView.animateWithDuration(0.25) { 
        
        // 更新布局
        self.view.layoutIfNeeded()
        
        }
        
        
    }
    
    //// 移除通知
    deinit{
    
     NSNotificationCenter.defaultCenter().removeObserver(self)
    
    }
    
    
   
    // MARK: -  设置导航
    private func setUpNav(){
    
     navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
    
     navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
        
        // 右侧按钮不能点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        navigationItem.titleView = titleView
    }
    
    @objc private func cancel(){
    //结束编辑
    view.endEditing(true)
     
//    composeTextView.resignFirstResponder()
    self.dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    /*
     A[马到成功]a       发送到服务器  显示在我们app的首页或者pc端 显示A表情a
     */
    @objc private func send(){
    
//     print("send")
                print("发送微博")
        //        print(composeTextView.attributedText)
        /*
         闭包中参数
         01- 遍历的结果
         02- 遍历范围
         04 - 是否停止遍历
         */
        
        var resultStr = ""
     // 遍历富文本
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0,length: composeTextView.attributedText.length) ,options: []) { (dict, range, _) in
            
            // 如果是文本附件
            if let att = dict["NSAttachment"] as? WTTextAttachment{
            
             resultStr += (att.emoticon?.chs ?? "")
            
            }else{
               // 文字
              let name = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                
                resultStr += name
            
            }
        }
        
        // 如果配图中的数组.count > 0 代表发送有图片微博

        if pictureView.imageList.count > 0 {
            
            upload(resultStr)
        }else{
           
            update(resultStr)

        
        }
        
}
    
    // MARK: - 懒加载控件
    private lazy var titleView: UILabel = {
      //显示的文字
      let name = WTUserAccountTools.sharedUserAccountTools.userAccount?.screen_name ?? ""
        //最终显示的文字
      let str = "发微博\n\(name)"
       //获得range
        let range = (str as NSString).rangeOfString(name)
      // 富文本
        let attr = NSMutableAttributedString(string: str)
      // 设置富文本
        attr.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(13),NSForegroundColorAttributeName:ThemeColor], range: range)
        
        let label = UILabel()
        label.attributedText = attr
        label.textAlignment = .Center
        label.numberOfLines = 0
        label.sizeToFit()
        return label
     
    }()
    
     // textView
    private lazy var composeTextView: WTComposeTextView = {
    
     let textVeiw = WTComposeTextView()
    
    textVeiw.placeholder = "分享新鲜事....每天都有新的事物,新鲜的事情,愉快的;悲伤的,你的喜怒哀乐,分享你的朋友!!!!!"
        
     textVeiw.delegate = self
     //允许textView 上下拖动
        textVeiw.alwaysBounceVertical = true
        // 设置font
        textVeiw.font = UIFont.systemFontOfSize(16)
        
        return textVeiw
    
   }()
    
    // 底部toolbar
    private lazy var composeToolbar:WTComposeToolbar = WTComposeToolbar()
    
    //发布微博的配图
    private lazy var pictureView: WTComposePictureView = WTComposePictureView()
    
    // 自定义表情键盘
    private lazy var keyboarView: WTEmoticonKeyboard = {
       
        let view = WTEmoticonKeyboard()
        view.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 216)
        
        return view
    }()
}
// 处理toolbar按钮点击事件
extension WTComposeViewController{
    // 选择图片
    func selectImages(){
    
        let picker = UIImagePickerController()
        // 设置代理
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    
    }

    // 切换键盘
    func selectKeyboard() {
        /*
         如果判断当前显示的系统键盘 还是 自定义表情键盘
         */
        // 代表是系统键盘
        if composeTextView.inputView == nil {
            // 切换成自定义键盘
            composeTextView.inputView = keyboarView
             // 告知composeToolbar 键盘样式
            composeToolbar.isEmotion = true
        }else{
            // 代表是自定义键盘
            // 切换成系统键盘
           composeTextView.inputView = nil
            // 告知composeToolbar 键盘样式
            composeToolbar.isEmotion = false
        
        }
        // 刷新inputView
        composeTextView.reloadInputViews()
        // 成为第一响应者
        composeTextView.becomeFirstResponder()
    }
    
    


}
//UIImagePickerController 代理方法
extension WTComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
//        let date = UIImagePNGRepresentation(image)
//        date?.writeToFile("/Users/Wellim/Desktop/我哈.png", atomically: true)
        
//        let date = UIImagePNGRepresentation(scaleImageOfWidth(600, image: image))
//        date?.writeToFile("/Users/Wellim/Desktop/我哈1.png", atomically: true)
        //压缩图片方式2
//        let date2 = UIImageJPEGRepresentation(image, 0.2)
//        date2?.writeToFile("/Users/Wellim/Desktop/我哈2.png", atomically: true)
        
        
        
//        print(image)
        // 填充图片
        pictureView.addImages(scaleImageOfWidth(600, image: image))
        
//        composeTextView.backgroundColor = UIColor(patternImage: image)
        
         // 如果实现代理方法 系统将不再帮程序员关闭控制器
        picker.dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    /*
     1200     压缩后的结果  600
     600                 x = 300
     如果 传入的宽度为500  原图返回
     */
    // 压缩图片 方式一
    func scaleImageOfWidth(width:CGFloat,image:UIImage) ->UIImage{
    // 如果传入的图片宽度小于我们制定压缩宽度的话 直接返回
        if width > image.size.width {
            
            return image
        }
       // 等比例计算出图片的高度
        let hight = (width * image.size.height) / image.size.width
         // 创建一个rect
        let rect = CGRect(x: 0, y: 0, width: width, height: hight)
         // 01- 开启上下文
        UIGraphicsBeginImageContext(rect.size)
        // 02- 将image 渲染到上下文中
        image.drawInRect(rect)
        // 03- 获取上下文的结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        // 04- 关闭上下文
        UIGraphicsEndImageContext()
        
        return result
    
    }


}

// 发送微博请求
extension WTComposeViewController{
  // 发送文字微博
    func update(status: String) {
        
        WTNetworktools.sharedNetworktools.composeUpdate(status, success: { (resposnse) in
            
            print("发送成功")
            
            }) { (error) in
                
                print("发送失败\(error)")
        }
        
        
    }
    
    /*
     通过该接口发送有图片微博 不管你发送多少张 微博服务器只接受你最后一张
     */
    // 上传图片且有文字微博
    
    func upload(status: String)  {
        
        WTNetworktools.sharedNetworktools.composeUpload(status, imageList: pictureView.imageList, success: { (resposnse) in
            print("发送成功")
            }) { (error) in
                 print("发送失败")
                
        }
        
        
    }
 




}

extension WTComposeViewController:UITextViewDelegate{
  // 监听textView 的文字改变
    
    func textViewDidChange(textView: UITextView) {
        
       navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }

    //停止拽动
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
//        self.view.endEditing(true)
        composeTextView.resignFirstResponder()
    }


}
